<?php
declare(strict_types=1);

namespace App\Middleware\Api;

use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use App\Constants\ReturnCode;
use Qbhy\HyperfAuth\AuthManager;
/**
 * Undocumented 管理后台用户登录token认证
 */
class AuthMiddleware implements MiddlewareInterface
{
    protected ContainerInterface $container;

    protected RequestInterface $request;

    protected HttpResponse $response;
    
    protected AuthManager $auth;
    public function __construct(ContainerInterface $container, HttpResponse $response, RequestInterface $request, AuthManager $auth)
    {
        $this->container = $container;
        $this->response = $response;
        $this->request = $request;
        $this->auth = $auth;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        
        $token = $this->request->input('token');
        $is_login = $this->auth->guard('app')->check($token);
        if ($is_login) {
            $payload = $this->auth->guard('app')->getPayload($token);
            $request = $request->withAttribute('user_id', $payload['uid']);
            return $handler->handle($request);
        }
        return $this->response->json(
            [
                'code' => ReturnCode::token_error,
                'message'=>ReturnCode::getMessage(ReturnCode::token_error)
            ]
        );
    }
}
